using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using OfficeOpenXml;

namespace Framework.DataTable
{
    public class DataTableConfigExcel : DataTableConfigTsv
    {
        public override void ReadFile(string path)
        {
            var list = new List<string>();
            var fileInfo = new FileInfo(path);
            _builder.Clear();
            using (ExcelPackage excelPackage = new ExcelPackage(fileInfo))
            {
                //读取Excel中的第一张表， 注意EPPlus的索引值是从1开始的
                var book = excelPackage.Workbook;
                var sheets = book.Worksheets;
                ExcelWorksheet worksheet = sheets[1];

                int lineStart = worksheet.Dimension.Start.Row;
                int lineEnd = worksheet.Dimension.End.Row;

                int colStart = worksheet.Dimension.Start.Column;
                int colEnd = worksheet.Dimension.End.Column;
                int colCount = colEnd - colStart;
                if (colCount > 50)
                {
                    FrameworkLog.LogErrorFormat("{0} 定义的字段总量 {1} 为异常数量", path, colCount);
                }
                for (int line = lineStart; line <= lineEnd; line++)
                {
                    _builder.Clear();
                    for (var col = colStart; col <= colEnd; col++)
                    {
                         var cellValue = worksheet.GetValue(line, col);
                        // 检查单元格的内容是否为数字，并将其格式化为字符串，避免科学计数法
                        if (cellValue is double || cellValue is float || cellValue is decimal || cellValue is long)
                        {
                            // 使用无科学计数法的数字格式输出
                            cellValue = Convert.ToDouble(cellValue).ToString("G", CultureInfo.InvariantCulture);
                        }
                        string cellText = cellValue?.ToString() ?? string.Empty;
                        if (col > colStart)
                        {
                            _builder.Append("\t");
                        }
                        _builder.Append(cellText);
                    }
                    list.Add(_builder.ToString());
                }
                var tsv = path + ".txt";
                if (File.Exists(tsv))
                {
                    File.Delete(tsv);
                }
                File.WriteAllLines(tsv, list, System.Text.Encoding.UTF8);
                base.ReadFile(tsv);
            }
        }
    }
}